﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SIA.Configurators;
using System.Net.Sockets;

namespace SIA.HwAccess.PLCSiemens.ConnectionDriver
{
    public class TCPOpenConnection : TCPClientConnection
    {
        //protected Byte[] _readBuffer;
        //protected Byte[] _writeBuffer;
        protected int _readLen;
        protected int _writeLen;

        public TCPOpenConnection(IDictionaryProperty ConnectionProperty, IDictionaryProperty signalsProperty)
            : base(ConnectionProperty, signalsProperty)
        {
            //if (!connectionProperty.ContainsKey("READLEN")) throw new ArgumentException(this.ToString() + ": Impossibile trovare la Proprietà: 'READLEN'");
            //if (!connectionProperty.ContainsKey("WRITELEN")) throw new ArgumentException(this.ToString() + ": Impossibile trovare la Proprietà: 'WRITELEN'");

            _readLen = ConnectionProperty.ContainsKey("READLEN") ? int.Parse(ConnectionProperty["READLEN"].PropertyValue) : 512;
            _writeLen = ConnectionProperty.ContainsKey("WRITELEN") ? int.Parse(ConnectionProperty["WRITELEN"].PropertyValue) : 512;
            //_rawData = new Dictionary<string,byte[]>();
            _rawData.Add("RAW_WRITE", new Byte[_writeLen]);
            _rawData.Add("RAW_READ", new Byte[_readLen]);
            //_readBuffer = new Byte[_readLen];
            //_writeBuffer = new Byte[_writeLen];
        }



        public override void update()
        {
            if (_socket == null || !_socket.Connected) connect();
            if (_socket == null || !_socket.Connected) _status = eConnectionStatus.ERROR;

            try
            {
                if (_writeLen > 0)
                    _socket.Send(_rawData["RAW_WRITE"].ToArray(), SocketFlags.None);

                if (_readLen > 0)
                {
                    List<Byte> bytesReceived = new List<Byte>(_readLen);
                    Byte[] reciveBuffer = new Byte[_readLen];
                    int bytes = 0;
                    do
                    {
                        bytes = _socket.Receive(reciveBuffer);
                        bytesReceived.AddRange(reciveBuffer);
                    }
                    while (bytes < _readLen);

                    if (_rawData["RAW_READ"].Length < _readLen)
                    {
                        _rawData["RAW_READ"] = new Byte[_readLen];
                    }

                    for (int i = 0; i < _readLen; i++)
                    {
                        _rawData["RAW_READ"][i] = bytesReceived[i];
                    }
                }
            }
            catch (Exception ex)
            {
                SIA.Messages.MessageManager.sendMessage(this, ex.Message, SIA.Messages.eMessageType.WARNING);
            }
        }

        public override void register(IHwSignal signal)
        {
            if (signal is S7Signal)
                if (!_signals.ContainsKey(signal.Name))
                {
                    _signals.Add(signal.Name, signal);                   
                    signal.Connection = this;
                }
        }

    }

}
